package com.zcareu.logServ.controller;

import com.zcareu.logServ.entity.Role;
import com.zcareu.logServ.entity.User;
import com.zcareu.logServ.repo.RoleRepo;
import com.zcareu.logServ.repo.UserRepo;
import org.apache.shiro.authc.credential.PasswordMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.*;

@RestController
public class UserController {

    @Autowired
    private PasswordMatcher passwordMatcher;

    @Autowired
    private UserRepo userRepo;

    @Autowired
    private RoleRepo roleRepo;


    @PostMapping(value = "/user")
    public User save(@RequestParam String username, @RequestParam String password, @RequestParam String roleName) {
        return userRepo.save(new User(username, passwordMatcher.getPasswordService().encryptPassword(password), Arrays.asList(roleRepo.findByName(roleName))));
    }

    @GetMapping(value = "/user")
    public List<Map<String, Serializable>> index(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer size) {
        List<Map<String, Serializable>> result = new LinkedList<>();

        for(User user : userRepo.findAll(PageRequest.of(page, size))) {
            Map<String, Serializable> record = new LinkedHashMap<>();

            record.put("username", user.getUsername());

            LinkedList<String> roles = new LinkedList<>();
            for(Role role : user.getRoles()) {
                roles.add(role.getName());
            }
            record.put("roles", roles);

            result.add(record);
        }

        return result;
    }
}
